package com.zx.idc.backend.gui.api.ftp.basic;

import com.zx.idc.backend.gui.api.ftp.FtpClientConfig;
import com.zx.idc.common.pool.ObjectFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BasicFtpClientFactory implements ObjectFactory<FTPClient> {

    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * ftp配置
     */
    private FtpClientConfig ftpClientConfig;

    public BasicFtpClientFactory(FtpClientConfig config) {
        this.ftpClientConfig = config;
    }

    @Override
    public FTPClient createNew() {
        final FTPClient ftp = new FTPClient();
        try {
            ftp.connect(ftpClientConfig.getHost(), ftpClientConfig.getPort());
            ftp.login(ftpClientConfig.getUsername(), ftpClientConfig.getPassword());
            //如果支持本地就使用 utf-8
            if (FTPReply.isPositiveCompletion(ftp.sendCommand(
                "OPTS UTF8", "ON"))) {
                ftpClientConfig.setLocalCharset("UTF-8");
            }
            //客户端被动模式
            ftp.enterLocalPassiveMode();
            //文件传输形式
            ftp.setFileType(ftpClientConfig.getFileType());
            //编码格式
            ftp.setControlEncoding(ftpClientConfig.getLocalCharset());
            return ftp;
        } catch (Throwable e) {
            log.error("ftp operation failed: {}", e);
            throw new RuntimeException(e);
        }
    }
}
